#!/usr/bin/env python
"""
Export.py

This class handles the exporting of a site in a directory listed in
DocumentRoot into a tar-file.
- Roland Arnold

"""

def _(s): return s

import os, wx, sys, tarfile, string
import  wx.wizard as wiz

from conf import Apache
from images import Image
from operations import UserMessage

class Export(wiz.Wizard):
    def __init__(self, prnt, myapache):
        wiz.Wizard.__init__(self, prnt, -1, _("Export Site"),
                            Image.bitmap("export_wizard.png"))
        d = myapache.get_directive("DocumentRoot").args.strip('"')
        self.li2 = [os.path.join(d, i) for i in os.listdir(d)
              if os.path.isdir(os.path.join(d, i))]
        self.li2.sort()
        self.li = [os.path.basename(d) for d in self.li2]
        self.selectedSite = self.li2[0]
        self.exportdir = os.path.expanduser("~")
        self.page1 = self.getPageOne()
        self.page2 = self.getPageTwo()
        wiz.WizardPageSimple_Chain(self.page1, self.page2)
        wiz.WizardPageSimple_Chain(self.page2, wiz.WizardPageSimple(self))
        prnt.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
        prnt.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnPageChanged)
        self.RunWizard(self.page1)
    
    def OnPageChanging(self, evt):
        self.OnTrackDir(None)
        if self.GetCurrentPage() == self.page2:
            if not evt.GetDirection():
                wx.FindWindowById(wx.ID_FORWARD).Enable()
            else:
                self.exportToFile()
                evt.Veto()
    
    def OnPageChanged(self, evt):
        if self.GetCurrentPage() == self.page1:
            wx.FindWindowById(wx.ID_FORWARD).SetLabel(_("&Next >"))
        elif self.GetCurrentPage() == self.page2:
            wx.FindWindowById(wx.ID_FORWARD).SetLabel(_("&Export"))
    
    def getPageOne(self):
        page = wiz.WizardPageSimple(self)
        sizer = wx.BoxSizer(wx.VERTICAL)
        st = wx.StaticText(page, -1, _("Select Site"))
        st.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD))
        sizer.Add(st, 0, wx.ALIGN_CENTER|wx.ALL, 5)
        sizer.Add(wx.StaticLine(page, -1), 0, wx.EXPAND|wx.ALL, 5)
        sizer.AddSpacer((-1, 50))
        st = wx.StaticText(page, -1, _("Select the website to export:"))
        sizer.Add(st, 0, wx.ALIGN_LEFT|wx.ALL, 5)
        self.SiteChoice = wx.Choice(page, -1, choices=self.li,
                                    size=wx.Size(240, -1))
        self.Bind(wx.EVT_CHOICE, self.OnChoiceEvt, self.SiteChoice)
        sizer.Add(self.SiteChoice, 0, wx.ALIGN_LEFT|wx.ALL, 5)
        page.SetSizer(sizer)
        return page
    
    def OnChoiceEvt(self, evt):
        self.selectedSite = self.li2[self.SiteChoice.GetSelection()]
    
    def getPageTwo(self):
        page = wiz.WizardPageSimple(self)
        sizer = wx.BoxSizer(wx.VERTICAL)
        st = wx.StaticText(page, -1, _("Select Directory"))
        st.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD))
        sizer.Add(st, 0, wx.ALIGN_CENTER|wx.ALL, 5)
        sizer.Add(wx.StaticLine(page, -1), 0, wx.EXPAND|wx.ALL, 5)
        sizer.AddSpacer((-1, 50))
        st = wx.StaticText(page, -1, _("Set the directory to export to:"))
        sizer.Add(st, 0, wx.ALIGN_LEFT|wx.ALL, 5)
        self.txtctrl = wx.TextCtrl(page, -1, self.exportdir,
                                   size=wx.Size(240, -1))
        self.Bind(wx.EVT_TEXT, self.OnTrackDir, self.txtctrl)
        sizer.Add(self.txtctrl, 0, wx.ALIGN_LEFT|wx.ALL, 5)
        self.SelectDirButton = wx.Button(page, -1,
                         _("Change Directory"), size=wx.Size(180, -1))
        self.Bind(wx.EVT_BUTTON, self.OnSelectDir, self.SelectDirButton)
        sizer.Add(self.SelectDirButton, 0, wx.ALIGN_LEFT|wx.ALL, 5)
        page.SetSizer(sizer)
        return page
    
    def OnSelectDir(self, evt):
        d = wx.DirDialog(self, style=wx.DD_NEW_DIR_BUTTON |
                         wx.DD_DEFAULT_STYLE, defaultPath=self.exportdir)
        if d.ShowModal() == wx.ID_OK:
            self.exportdir = d.GetPath()
            self.txtctrl.SetValue(d.GetPath())
    
    def OnTrackDir(self, evt):
        self.exportdir = self.txtctrl.GetValue()
        if os.path.exists(self.txtctrl.GetValue()):
            wx.FindWindowById(wx.ID_FORWARD).Enable()
        else:
            wx.FindWindowById(wx.ID_FORWARD).Disable()
    
    def exportToFile(self):
        fname = "%s.tar" % os.path.basename(self.selectedSite)
        fname = os.path.join(self.exportdir, fname)
        tar = tarfile.open(fname, "w")
        max = 0
        for root, dirs, files in os.walk(self.selectedSite):
            for name in files:
                max += 1
        oldwd = os.getcwd()
        os.chdir(os.path.split(self.selectedSite)[0])
        if len(os.listdir(os.path.split(self.selectedSite)[1])) == 0:
            tar.add(os.path.split(self.selectedSite)[1])
        l = len(os.path.split(self.selectedSite)[0] + os.sep)
        dlg = wx.ProgressDialog(_("Exporting Site"),
                               _("Exporting..."),
                               maximum=max, parent=self,
                               style = wx.PD_CAN_ABORT | wx.PD_APP_MODAL |
                               wx.PD_ELAPSED_TIME | wx.PD_ESTIMATED_TIME |
                               wx.PD_REMAINING_TIME)
        keepGoing = True
        count = 0
        while keepGoing and count < max:
            for root, dirs, files in os.walk(self.selectedSite):
                root = root[l:]
                for name in files:
                    tar.add(os.path.join(root, name))
                    count += 1
                    keepGoing = dlg.Update(count)
                    if not keepGoing:
                        break
                if not keepGoing:
                    break
        dlg.Destroy()
        if not keepGoing:
            tar.close()
            os.remove(fname)
            UserMessage.say(_("Export cancelled"), _("Cancelled"))
        else:
            tar.close()
            self.Hide()
            os.chdir(oldwd)
            UserMessage.say(_("Website succesfully exported"), _("Success!"))
    
if __name__ == "__main__":
    app = wx.PySimpleApp()
    mf = Export(wx.Frame(None, -1, ""),
                Apache.Apache("/etc/apache2/apache2.conf"))
    sys.exit()
#    app.MainLoop()
